package uvt.gui.mainframe.subpanel.addroute;

import javax.swing.JButton;
import javax.swing.JComboBox;

import uvt.database.Database;
import uvt.database.InsertOperations;
import uvt.gui.mainframe.object.InfoFrame;
import uvt.gui.mainframe.object.command.Command;
import uvt.gui.mainframe.object.memento.ButtonOperations;
import uvt.gui.mainframe.object.memento.MementoImp;
import uvt.gui.mainframe.object.memento.container.ButtonOperationBackup;
import uvt.gui.mainframe.object.memento.container.Container;
import uvt.gui.mainframe.object.observer.ConcreteObservable;

public class AddRouteButton extends JButton implements Command {

	private RouteNameTextField txtName;
	private MementoImp memento;
	private JButton undo;
	private JComboBox<String> type;
	
	public AddRouteButton(RouteNameTextField f1,MementoImp memento,JButton undo,JComboBox<String> type) {
		super("Add Route");
		this.txtName = f1;
		this.memento = memento;
		this.undo = undo;
		this.type = type;
	}
	
	public void execute() {
		try {
			validateTextFields();
			((InsertOperations)Database.getInstace()).insertRowRouteName(txtName.getText(),type.getSelectedItem().toString());
			ConcreteObservable.getRoutePanelObservableInstance().stateChanged();
			memento.setContainer(new Container(txtName.getText()));
			ButtonOperationBackup.getInstance().addReference(ButtonOperations.ADDROUTE,memento.backup());
			undo.setEnabled(true);
			Thread t = new Thread(new Runnable() {
				public void run() {
					new InfoFrame("Information","Route was added in database!");
			    }
			});
			t.start();
		} catch(final Exception ex) {
			Thread t = new Thread(new Runnable() {
				public void run() {
					new InfoFrame("Error",ex.getMessage());
				}
			});
			t.start();
		}
		
	}
	
	public void validateTextFields() throws Exception {
		if(txtName.getText().equals("")) throw new Exception("Route name field empty!");		
	}
	
}
